from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.utils import timezone
from .models import (
    SystemMetric, MetricData, SystemAlert, HealthCheck,
    PerformanceLog, SystemConfiguration, MonitoringDashboard
)

User = get_user_model()


class SystemMetricSerializer(serializers.ModelSerializer):
    """
    系统指标序列化器
    """
    metric_type_display = serializers.CharField(source='get_metric_type_display', read_only=True)
    
    class Meta:
        model = SystemMetric
        fields = [
            'id', 'name', 'metric_type', 'metric_type_display', 'description', 'unit',
            'warning_threshold', 'critical_threshold', 'collection_interval',
            'retention_days', 'is_active', 'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def validate(self, data):
        """
        验证阈值设置
        """
        warning_threshold = data.get('warning_threshold')
        critical_threshold = data.get('critical_threshold')
        
        if warning_threshold is not None and critical_threshold is not None:
            if warning_threshold >= critical_threshold:
                raise serializers.ValidationError(
                    '警告阈值必须小于严重阈值'
                )
        
        return data


class MetricDataSerializer(serializers.ModelSerializer):
    """
    指标数据序列化器
    """
    metric_name = serializers.CharField(source='metric.name', read_only=True)
    metric_unit = serializers.CharField(source='metric.unit', read_only=True)
    is_warning = serializers.BooleanField(read_only=True)
    is_critical = serializers.BooleanField(read_only=True)
    
    class Meta:
        model = MetricData
        fields = [
            'id', 'metric', 'metric_name', 'metric_unit', 'value', 'timestamp',
            'tags', 'metadata', 'is_warning', 'is_critical'
        ]
        read_only_fields = ['is_warning', 'is_critical']


class SystemAlertSerializer(serializers.ModelSerializer):
    """
    系统告警序列化器
    """
    metric_name = serializers.CharField(source='metric.name', read_only=True)
    alert_level_display = serializers.CharField(source='get_alert_level_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    acknowledged_by_username = serializers.CharField(source='acknowledged_by.username', read_only=True)
    resolved_by_username = serializers.CharField(source='resolved_by.username', read_only=True)
    duration = serializers.SerializerMethodField()
    
    class Meta:
        model = SystemAlert
        fields = [
            'id', 'metric', 'metric_name', 'alert_level', 'alert_level_display',
            'title', 'message', 'trigger_value', 'threshold_value',
            'status', 'status_display', 'triggered_at', 'acknowledged_at', 'resolved_at',
            'acknowledged_by', 'acknowledged_by_username', 'resolved_by', 'resolved_by_username',
            'tags', 'metadata', 'duration'
        ]
        read_only_fields = [
            'triggered_at', 'acknowledged_at', 'resolved_at',
            'acknowledged_by', 'resolved_by', 'duration'
        ]
    
    def get_duration(self, obj):
        """
        获取告警持续时间（秒）
        """
        if obj.duration:
            return obj.duration.total_seconds()
        return None


class HealthCheckSerializer(serializers.ModelSerializer):
    """
    健康检查序列化器
    """
    check_type_display = serializers.CharField(source='get_check_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    uptime_percentage = serializers.ReadOnlyField()
    
    class Meta:
        model = HealthCheck
        fields = [
            'id', 'name', 'check_type', 'check_type_display', 'description',
            'endpoint', 'timeout', 'interval', 'status', 'status_display',
            'last_check_time', 'last_success_time', 'success_count', 'failure_count',
            'last_error', 'uptime_percentage', 'is_active', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'status', 'last_check_time', 'last_success_time',
            'success_count', 'failure_count', 'last_error',
            'uptime_percentage', 'created_at', 'updated_at'
        ]
    
    def validate_timeout(self, value):
        """
        验证超时时间
        """
        if value <= 0 or value > 300:  # 最大5分钟
            raise serializers.ValidationError('超时时间必须在1-300秒之间')
        return value
    
    def validate_interval(self, value):
        """
        验证检查间隔
        """
        if value < 10:  # 最小10秒
            raise serializers.ValidationError('检查间隔不能少于10秒')
        return value


class PerformanceLogSerializer(serializers.ModelSerializer):
    """
    性能日志序列化器
    """
    log_type_display = serializers.CharField(source='get_log_type_display', read_only=True)
    username = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = PerformanceLog
        fields = [
            'id', 'log_type', 'log_type_display', 'operation', 'duration_ms',
            'memory_usage_mb', 'cpu_usage_percent', 'user', 'username',
            'ip_address', 'user_agent', 'request_data', 'response_data',
            'success', 'error_message', 'timestamp'
        ]
        read_only_fields = ['timestamp']


class SystemConfigurationSerializer(serializers.ModelSerializer):
    """
    系统配置序列化器
    """
    config_type_display = serializers.CharField(source='get_config_type_display', read_only=True)
    last_modified_by_username = serializers.CharField(source='last_modified_by.username', read_only=True)
    masked_value = serializers.SerializerMethodField()
    
    class Meta:
        model = SystemConfiguration
        fields = [
            'id', 'name', 'config_type', 'config_type_display', 'description',
            'config_value', 'masked_value', 'default_value', 'validation_rules',
            'is_active', 'is_sensitive', 'last_modified_by', 'last_modified_by_username',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['last_modified_by', 'created_at', 'updated_at']
    
    def get_masked_value(self, obj):
        """
        获取脱敏后的配置值
        """
        return obj.get_masked_value()
    
    def validate_config_value(self, value):
        """
        验证配置值
        """
        # 这里可以根据validation_rules进行验证
        # 简单示例：检查是否为空
        if not value:
            raise serializers.ValidationError('配置值不能为空')
        return value


class MonitoringDashboardSerializer(serializers.ModelSerializer):
    """
    监控仪表板序列化器
    """
    created_by_username = serializers.CharField(source='created_by.username', read_only=True)
    allowed_users_count = serializers.SerializerMethodField()
    can_edit = serializers.SerializerMethodField()
    
    class Meta:
        model = MonitoringDashboard
        fields = [
            'id', 'name', 'description', 'layout', 'widgets',
            'is_public', 'allowed_users', 'allowed_users_count',
            'auto_refresh', 'refresh_interval', 'created_by',
            'created_by_username', 'can_edit', 'is_active',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['created_by', 'created_at', 'updated_at']
    
    def get_allowed_users_count(self, obj):
        """
        获取允许访问的用户数量
        """
        return obj.allowed_users.count()
    
    def get_can_edit(self, obj):
        """
        检查当前用户是否可以编辑
        """
        request = self.context.get('request')
        if request and request.user:
            return obj.created_by == request.user
        return False
    
    def validate_refresh_interval(self, value):
        """
        验证刷新间隔
        """
        if value < 5:  # 最小5秒
            raise serializers.ValidationError('刷新间隔不能少于5秒')
        return value
    
    def validate_widgets(self, value):
        """
        验证组件配置
        """
        if not isinstance(value, list):
            raise serializers.ValidationError('组件配置必须是数组格式')
        
        # 验证每个组件的基本结构
        for widget in value:
            if not isinstance(widget, dict):
                raise serializers.ValidationError('组件配置必须是对象格式')
            
            if 'id' not in widget or 'type' not in widget:
                raise serializers.ValidationError('组件必须包含id和type字段')
        
        return value


class MetricStatisticsSerializer(serializers.Serializer):
    """
    指标统计序列化器
    """
    avg_value = serializers.FloatField()
    max_value = serializers.FloatField()
    min_value = serializers.FloatField()
    count = serializers.IntegerField()
    warning_violations = serializers.IntegerField()
    critical_violations = serializers.IntegerField()
    time_range = serializers.DictField()


class AlertSummarySerializer(serializers.Serializer):
    """
    告警摘要序列化器
    """
    status_stats = serializers.ListField()
    level_stats = serializers.ListField()
    recent_alerts_24h = serializers.IntegerField()
    active_alerts = serializers.IntegerField()


class HealthStatusSerializer(serializers.Serializer):
    """
    健康状态序列化器
    """
    status_stats = serializers.ListField()
    total_checks = serializers.IntegerField()
    healthy_checks = serializers.IntegerField()
    health_percentage = serializers.FloatField()


class PerformanceStatsSerializer(serializers.Serializer):
    """
    性能统计序列化器
    """
    overall_stats = serializers.DictField()
    operation_stats = serializers.ListField()
    time_range = serializers.DictField()


class SystemOverviewSerializer(serializers.Serializer):
    """
    系统概览序列化器
    """
    metrics = serializers.DictField()
    alerts = serializers.DictField()
    health_checks = serializers.DictField()
    performance = serializers.DictField()
    timestamp = serializers.DateTimeField()


class DashboardDataSerializer(serializers.Serializer):
    """
    仪表板数据序列化器
    """
    dashboard = MonitoringDashboardSerializer()
    widget_data = serializers.ListField()
    last_updated = serializers.DateTimeField()


class WidgetDataSerializer(serializers.Serializer):
    """
    组件数据序列化器
    """
    widget_id = serializers.CharField()
    type = serializers.CharField()
    data = serializers.JSONField()
    error = serializers.CharField(required=False)


class MetricCollectionSerializer(serializers.Serializer):
    """
    指标收集序列化器
    """
    metric_name = serializers.CharField(max_length=100)
    metric_type = serializers.ChoiceField(choices=SystemMetric.METRIC_TYPES)
    value = serializers.FloatField()
    timestamp = serializers.DateTimeField(required=False)
    unit = serializers.CharField(max_length=20, required=False)
    description = serializers.CharField(required=False)
    tags = serializers.DictField(required=False, default=dict)
    
    def validate_value(self, value):
        """
        验证指标值
        """
        if value < 0:
            raise serializers.ValidationError('指标值不能为负数')
        return value


class HealthCheckExecutionSerializer(serializers.Serializer):
    """
    健康检查执行结果序列化器
    """
    health_check_id = serializers.IntegerField()
    name = serializers.CharField()
    success = serializers.BooleanField()
    error = serializers.CharField(required=False)
    duration_ms = serializers.FloatField(required=False)
    timestamp = serializers.DateTimeField(required=False)


class AlertActionSerializer(serializers.Serializer):
    """
    告警操作序列化器
    """
    action = serializers.ChoiceField(choices=['acknowledge', 'resolve', 'suppress'])
    comment = serializers.CharField(required=False, max_length=500)
    
    def validate_action(self, value):
        """
        验证操作类型
        """
        valid_actions = ['acknowledge', 'resolve', 'suppress']
        if value not in valid_actions:
            raise serializers.ValidationError(f'无效的操作类型，支持的操作: {", ".join(valid_actions)}')
        return value


class DashboardShareSerializer(serializers.Serializer):
    """
    仪表板分享序列化器
    """
    user_ids = serializers.ListField(
        child=serializers.IntegerField(),
        required=False,
        default=list
    )
    is_public = serializers.BooleanField(default=False)
    
    def validate_user_ids(self, value):
        """
        验证用户ID列表
        """
        if value:
            # 检查用户是否存在
            existing_users = User.objects.filter(id__in=value).values_list('id', flat=True)
            invalid_ids = set(value) - set(existing_users)
            
            if invalid_ids:
                raise serializers.ValidationError(f'用户ID不存在: {list(invalid_ids)}')
        
        return value